package com.hw2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class Trie {

	Map<Character,CharP> root=new HashMap<Character,CharP>();
	
	public void readDictionary(String path){
		File file = new File(path);
		try(BufferedReader br = new BufferedReader(new FileReader(file))) {
		    for(String line; (line = br.readLine()) != null; ) {
		        // process the line.
		    	insert(line.trim());
		    }
		    // line is not visible here.
		    br.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void insert(String s){
		int len=s.length();
		Map<Character,CharP> cur=root;
		for(int i=0;i<len;i++){
			char c=s.charAt(i);
			if(!cur.containsKey(c)){
				CharP ch=new CharP(c);
				if(i==len-1)
					ch.setWord(true);
				cur.put(c, ch);
			}
			cur=cur.get(c).getChildren();
		}
	}
	
	
	public boolean isWord(String s){
		int len=s.length();
		Map<Character,CharP> cur=root;
		for(int i=0;i<len;i++){
			char c=s.charAt(i);
			if(cur.containsKey(c)){
				if(i==len-1)
					return cur.get(c).isWord();
				cur=cur.get(c).getChildren();
			}
			else{
				return false;
			}
		}
		return false;
	}
	
	
}
